
package net.swa.dewei.service.impl;

import net.swa.dewei.beans.entity.DingDanCard;
import net.swa.dewei.beans.entity.DingDanCardGoods;
import net.swa.dewei.beans.entity.FuwuZhan;
import net.swa.dewei.beans.entity.MenDian;
import net.swa.dewei.beans.vo.VoListPage;
import net.swa.dewei.service.DingDanCardService;
import net.swa.system.dao.HibernateDaoSupport;
import net.swa.util.BuzConst;
import net.swa.util.DateUtils;
import net.swa.util.JsonResult;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.stereotype.Service;

@Service("dingDanCardService")
public class DingDanCardServiceImpl extends HibernateDaoSupport implements DingDanCardService
{
    private static final Logger log = Logger.getLogger(DingDanCardServiceImpl.class);

    @Override
    public Map<String, Object> addDingdan(DingDanCard m)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);
        map.put("message", "订单数据缺失");
        if (null != m)
        {
            List<DingDanCardGoods> goods = m.getGoods();
            if (null != goods && goods.size() > 0)
            {
                String d = DateUtils.getCurrDate("yyyyMMddHHmmss");
                Session session = getCurrentSession();
                String r = null;
                m.setCrateDate(DateUtils.getCurrDate(null));
                m.setState(BuzConst.CARD_STATUS0);
                session.save(m);
                Long fid = m.getId();
                r = d + fid;
                m.setDingDanUid(r);
                session.update(m);
                for (DingDanCardGoods g : goods)
                {
                    g.setFid(fid);
                    session.save(g);
                }
                map.put("success", true);
                map.put("message", "");
                map.put("model", m);
            }
        }
        return map;
    }

    @Override
    public void batchUpdateState(final Long[] ids , String state)
    {
        Session session = getCurrentSession();
        Query query = session.createQuery("update DingDanCard set state=:state  where id=:id");
        for (int i = 0; i < ids.length; i++)
        {
            if (null != ids[i])
            {
                query.setLong("id", ids[i]);
                query.setString("state", state);
                query.executeUpdate();
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public DingDanCard queryById(final Long id)
    {
        Session session = getCurrentSession();
        DingDanCard m = null;
        Query query = session.createQuery(" from  DingDanCardGoods where fid=:fid");
        query.setLong("fid", id);
        List<DingDanCardGoods> l = query.list();
        if (null != l && l.size() > 0)
        {
            m = (DingDanCard) session.get(DingDanCard.class, id);
            m.setGoods(l);
            m.setAllPrice(BuzConst.add(m.getGoodsPrice(), m.getServicePrice()));
        }
        if (null != m.getMendianId())
        {
            MenDian mend = (MenDian) session.get(MenDian.class, m.getMendianId());
            if (null != mend)
            {
                m.setMendAddr(mend.getAddress());
                m.setMendImgUrl(mend.getImageUrl());
                m.setMendName(mend.getName());
                m.setMendLxr(mend.getLxr());
                m.setMendLxTel(mend.getLxrTel());
                if (null != mend.getFuwuzhanId())
                {
                    FuwuZhan fwz = (FuwuZhan) session.get(FuwuZhan.class, mend.getFuwuzhanId());
                    m.setFuwuzhanId(mend.getFuwuzhanId());
                    m.setFwzName(fwz.getName());
                }
            }
        }
        else
        {
            //上门服务的附上服务站
            //根据省市县 查询服务站，多个只取1个
            String hql = null;
            if (BuzConst.CARD_BUYTYPE_SM.equals(m.getBuyType()))
            {
                if (!StringUtils.isBlank(m.getProvince()))
                {
                    String p = m.getProvince();
                    if (p.length() > 3)
                    {
                        p.substring(0, 3);
                    }
                    if (!StringUtils.isBlank(m.getCity()))
                    {
                        String c = m.getCity();
                        if (c.length() > 3)
                        {
                            c.substring(0, 3);
                        }
                        if (!StringUtils.isBlank(m.getTown()))
                        {
                            String t = m.getTown();
                            if (t.length() > 3)
                            {
                                t.substring(0, 3);
                            }
                            hql = "from   FuwuZhan   where province like :province and city like :city and town like :town ";
                            Query q = getCurrentSession().createQuery(hql);
                            q.setString("province", p + "%");
                            q.setString("city", c + "%");
                            q.setString("town", t + "%");
                            List<FuwuZhan> fwzl = (List<FuwuZhan>) q.list();
                            if (null != fwzl && fwzl.size() > 0)
                            {
                                FuwuZhan f = fwzl.get(0);
                                if (!StringUtils.isBlank(f.getName()))
                                {
                                    m.setFuwuzhanId(f.getId());
                                    m.setFwzName(f.getName());
                                }
                            }
                            else
                            {
                                hql = "from   FuwuZhan   where province like :province and city like :city and (town ='' or town is null) ";
                                q = getCurrentSession().createQuery(hql);
                                q.setString("province", p + "%");
                                q.setString("city", c + "%");
                                List<FuwuZhan> l2 = (List<FuwuZhan>) q.list();
                                if (null != l2 && l2.size() > 0)
                                {
                                    FuwuZhan f = l2.get(0);
                                    if (!StringUtils.isBlank(f.getName()))
                                    {
                                        m.setFuwuzhanId(f.getId());
                                        m.setFwzName(f.getName());
                                    }
                                }
                                else
                                {
                                    hql = "from   FuwuZhan   where province like :province and (city ='' or city is null) ";
                                    q = getCurrentSession().createQuery(hql);
                                    q.setString("province", p + "%");
                                    List<FuwuZhan> l3 = (List<FuwuZhan>) q.list();
                                    if (null != l3 && l3.size() > 0)
                                    {
                                        FuwuZhan f = l3.get(0);
                                        if (!StringUtils.isBlank(f.getName()))
                                        {
                                            m.setFuwuzhanId(f.getId());
                                            m.setFwzName(f.getName());
                                        }
                                    }
                                    else
                                    {
                                        m.setFwzName(BuzConst.DEWEI_NAME);
                                    }
                                }
                            }

                        }
                    }
                }
            }
        }
        return m;
    }

    @SuppressWarnings("unchecked")
    @Override
    public DingDanCard queryDetailById(final Long id)
    {
        Session session = getCurrentSession();
        DingDanCard m = null;
        Query query = session.createQuery(" from  DingDanCardGoods where fid=:fid");
        query.setLong("fid", id);
        List<DingDanCardGoods> l = query.list();
        if (null != l && l.size() > 0)
        {
            StringBuilder sql = new StringBuilder();
            sql.append("select d.id,d.dingDanUid,userId,d.kehuName,d.lxTel,d.address,d.mendianId,d.buyType,d.goodsPrice,d.servicePrice, ");
            sql.append("d.lat,d.lng,d.crateDate,d.updateDate,d.state,d.province,d.city,d.town, ");
            sql.append("m.name as mendName,m.imageUrl as mendImgUrl,m.mendLxr,m.mendLxTel,m.mendAddr ");
            sql.append("f.id as fuwuzhanId,f.name as fwzName ");
            sql.append("from t_dingdan_card_main d  ");
            sql.append("left join t_mendian m on m.id=d.mendianId  ");
            sql.append("left join t_fuwuzhan f on m.fuwuzhanId =f.id  ");
            sql.append("where d.id=:id  ");
            query = session.createSQLQuery(sql.toString()).addScalar("id", StandardBasicTypes.LONG).addScalar("dingDanUid", StandardBasicTypes.STRING).addScalar("userId", StandardBasicTypes.STRING).addScalar("kehuName", StandardBasicTypes.STRING).addScalar("address", StandardBasicTypes.STRING).addScalar("mendianId", StandardBasicTypes.LONG).addScalar("buyType", StandardBasicTypes.STRING).addScalar("goodsPrice", StandardBasicTypes.DOUBLE).addScalar("servicePrice", StandardBasicTypes.DOUBLE).addScalar("lat",
                    StandardBasicTypes.DOUBLE).addScalar("lng", StandardBasicTypes.DOUBLE).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("state", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("mendName", StandardBasicTypes.STRING).addScalar("mendImgUrl", StandardBasicTypes.STRING)

            .addScalar("mendLxr", StandardBasicTypes.STRING).addScalar("mendLxTel", StandardBasicTypes.STRING).addScalar("mendAddr", StandardBasicTypes.STRING).addScalar("fuwuzhanId", StandardBasicTypes.LONG).addScalar("fwzName", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(DingDanCard.class));
            query.setLong("id", id);
            m = (DingDanCard) query.uniqueResult();
            if (null != m)
            {
                if (null == m.getMendianId())
                {
                    //若门店id不存在  则层层匹配，逻辑量大
                    if (m.getBuyType().equals(BuzConst.CARD_BUYTYPE_SM))
                    {
                        if (!StringUtils.isBlank(m.getProvince()))
                        {
                            String hql = "from   FuwuZhan   where province like :province ";
                            String p = m.getProvince();
                            String c = null, t = null;
                            if (p.length() > 3)
                            {
                                p.substring(0, 3);
                            }
                            if (!StringUtils.isBlank(m.getTown()))
                            {
                                t = m.getTown();
                                c = m.getCity() == null ? "" : m.getCity();
                                if (!StringUtils.isBlank(c) && (!c.equals(t)))
                                {
                                    hql = "from   FuwuZhan   where province like :province and city like :city and town like :town ";
                                }
                                else
                                {
                                    hql = "from   FuwuZhan   where province like :province  and town like :town ";
                                }
                            }
                            else if (!StringUtils.isBlank(m.getCity()))
                            {
                                c = m.getCity();
                                hql = "from   FuwuZhan   where province like :province and city like :city  ";
                            }
                            Query q = getCurrentSession().createQuery(hql);
                            q.setString("province", p + "%");
                            if (!StringUtils.isBlank(m.getTown()))
                            {
                                if (!StringUtils.isBlank(c) && (!c.equals(t)))
                                {
                                    if (t.length() > 3)
                                    {
                                        t = t.substring(0, 3);
                                    }
                                    if (c.length() > 3)
                                    {
                                        t = c.substring(0, 3);
                                    }
                                    q.setString("city", c + "%");
                                    q.setString("town", t + "%");

                                }
                                else
                                {
                                    if (t.length() > 3)
                                    {
                                        t = t.substring(0, 3);
                                    }
                                    q.setString("town", t + "%");
                                }
                            }
                            else if (!StringUtils.isBlank(m.getCity()))
                            {
                                if (c.length() > 3)
                                {
                                    c = c.substring(0, 3);
                                }
                                q.setString("city", c + "%");
                            }
                            List<FuwuZhan> l2 = (List<FuwuZhan>) q.list();
                            if (null != l2 && l2.size() > 0)
                            {
                                FuwuZhan f = l2.get(0);
                                if (!StringUtils.isBlank(f.getName()))
                                {
                                    m.setFuwuzhanId(f.getId());
                                    m.setFwzName(f.getName());
                                }
                            }
                            else
                            {
                                //若省市县没有拼配到服务站，向上拼配，到市
                                if (!StringUtils.isBlank(m.getCity()))
                                {
                                    hql = "from   FuwuZhan   where  province like :province and city like :city and (town ='请选择' or town is null)  ";
                                    q = getCurrentSession().createQuery(hql);
                                    q.setString("province", p + "%");
                                    q.setString("city", c + "%");
                                    l2 = (List<FuwuZhan>) q.list();
                                }
                                if (null != l2 && l2.size() > 0)
                                {
                                    FuwuZhan f = l2.get(0);
                                    if (!StringUtils.isBlank(f.getName()))
                                    {
                                        m.setFuwuzhanId(f.getId());
                                        m.setFwzName(f.getName());
                                    }
                                }
                                else
                                {
                                    //若省市县没有拼配到服务站，向上拼配，到省
                                    hql = "from   FuwuZhan   where  province like :province and (city ='请选择' or city is null)  ";
                                    q = getCurrentSession().createQuery(hql);
                                    q.setString("province", p + "%");
                                    l2 = (List<FuwuZhan>) q.list();
                                }
                                if (null != l2 && l2.size() > 0)
                                {
                                    FuwuZhan f = l2.get(0);
                                    if (!StringUtils.isBlank(f.getName()))
                                    {
                                        m.setFuwuzhanId(f.getId());
                                        m.setFwzName(f.getName());
                                    }
                                }
                                else
                                {
                                    m.setFwzName(BuzConst.DEWEI_NAME);
                                }
                            }
                        }
                    }
                }
                m.setInvalidDate(DateUtils.getDatePlusHour(m.getCrateDate(), BuzConst.FORMAT_STRING1, BuzConst.FORMAT_STRING2, BuzConst.HOUR48));
                m.setGoods(l);
            }
        }
        return m;
    }

    @Override
    public Map<String, Object> updateProcess(final Long id , String state , Long mendianId)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);
        map.put("message", "数据缺失");
        if (null != id && (!StringUtils.isBlank(state)))
        {
            Session session = getCurrentSession();
            Query query = session.createQuery("update DingDanCard set state=:state,updateDate=:updateDate  where id=:id");
            if (null != mendianId)
            {
                query = session.createQuery("update DingDanCard set mendianId=:mendianId,state=:state,updateDate=:updateDate  where id=:id");
                query.setLong("mendianId", mendianId);
            }
            query.setLong("id", id);
            query.setString("updateDate", DateUtils.getCurrDate(null));
            query.setString("state", state);
            query.executeUpdate();
            map.put("success", true);
            map.put("message", "success");
        }
        return map;
    }

    @Override
    public void delete(final Long[] ids)
    {
        Session session = getCurrentSession();
        Query query = session.createQuery("delete from DingDanCardGoods  where fid=:id");
        for (int i = 0; i < ids.length; i++)
        {
            if (null != ids[i])
            {
                query.setLong("id", ids[i]);
                query.executeUpdate();

                query = session.createQuery("delete from DingDanCard  where id=:id");
                query.setLong("id", ids[i]);
                query.executeUpdate();

            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public JsonResult<DingDanCard> queryDingdansPage(String customerName , String customerTel , String mendianName , String dingDanUid , String state , String buyType , Long fuwuZhanId , String fuwuzhanName , int currentPage , int pageSize , String orderBy , String orderType)
    {
        log.debug("queryDingdansPage");
        JsonResult<DingDanCard> json = new JsonResult<DingDanCard>();
        List<DingDanCard> list = null;
        Query query = null;
        Session session = getCurrentSession();

        String fwzIds = null;
        StringBuilder fwzStr = new StringBuilder();
        FuwuZhan fuwuzhan = null;
        if (null != fuwuZhanId)
        {
            fuwuzhan = (FuwuZhan) getCurrentSession().get(FuwuZhan.class, fuwuZhanId);
        }
        else if (!StringUtils.isBlank(fuwuzhanName))
        {
            if (StringUtils.isBlank(state) || state.equals(BuzConst.DINGDAN_STATES0) || state.equals(BuzConst.DINGDAN_STATES3) || state.equals(BuzConst.DINGDAN_STATES4))
            {
                String hq = "from FuwuZhan where  name like :name";
                Query qq = getCurrentSession().createQuery(hq);
                qq.setString("name", "%" + fuwuzhanName + "%");
                List<FuwuZhan> flist = qq.list();
                if (null != flist && flist.size() > 0)
                {
                    fwzIds = "";
                    if (StringUtils.isBlank(state))
                    {
                        fwzStr.append("or (d.buyType='" + BuzConst.CARD_BUYTYPE_SM + "' and d.state in ('0','3','4') and d.mendianId is null  and(");
                    }
                    else
                    {
                        fwzStr.append("or (d.buyType='" + BuzConst.CARD_BUYTYPE_SM + "'  and d.state='" + state + "' and d.mendianId is null   and(");
                    }
                    for (int i = 0; i < flist.size(); i++)
                    {
                        FuwuZhan f = flist.get(i);
                        if ((i + 1) == flist.size())
                        {
                            fwzIds += f.getId();
                            if (!StringUtils.isBlank(f.getProvince()) && (!"请选择".equals(f.getProvince())))
                            {
                                fwzStr.append("(d.province like '" + f.getProvince() + "%' ");
                                if (!StringUtils.isBlank(f.getCity()) && (!"请选择".equals(f.getCity())))
                                {
                                    fwzStr.append(" and d.city like '" + f.getCity().replace("市", "") + "%' ");
                                    if (!StringUtils.isBlank(f.getTown()) && (!"请选择".equals(f.getTown())))
                                    {
                                        fwzStr.append(" and d.town like '" + f.getTown() + "%' ");
                                    }
                                }
                                fwzStr.append(" )");
                            }
                            fwzStr.append(" ))");
                        }
                        else
                        {
                            fwzIds += f.getId() + ",";
                            if (!StringUtils.isBlank(f.getProvince()) && (!"请选择".equals(f.getProvince())))
                            {
                                fwzStr.append("(d.province like '" + f.getProvince() + "%' ");
                                if (!StringUtils.isBlank(f.getCity()) && (!"请选择".equals(f.getCity())))
                                {
                                    fwzStr.append(" and d.city like '" + f.getCity().replace("市", "") + "%' ");
                                    if (!StringUtils.isBlank(f.getTown()) && (!"请选择".equals(f.getTown())))
                                    {
                                        fwzStr.append(" and d.town like '" + f.getTown() + "%' ) or ");
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    return json;
                }
            }
            else
            {
                fwzIds = null;
                fwzStr.append(" and f.name like '%" + fuwuzhanName + "%' ");
            }
        }

        StringBuilder sql = new StringBuilder();
        StringBuilder count = new StringBuilder();

        sql.append("select d.id,d.dingDanUid,d.carNo,d.userId,d.kehuName,d.lxTel,d.address,d.mendianId,d.buyType,d.goodsPrice,d.servicePrice, ");
        sql.append("d.lat,d.lng,d.crateDate,d.updateDate,d.state,d.province,d.city,d.town, ");
        sql.append("m.name as mendName,m.imageUrl as mendImgUrl, ");
        sql.append("f.id as fuwuzhanId,f.name as fwzName ");

        sql.append("from t_dingdan_card_main d  ");
        sql.append("left join t_mendian m on m.id=d.mendianId  ");
        sql.append("left join t_fuwuzhan f on m.fuwuzhanId =f.id  ");

        count.append("select count(*) as countNum ");
        count.append("from t_dingdan_card_main d  ");
        count.append("left join t_mendian m on m.id=d.mendianId  ");
        count.append("left join t_fuwuzhan f on m.fuwuzhanId =f.id  ");

        sql.append("where 1=1  ");
        count.append("where 1=1  ");

        if (!StringUtils.isBlank(customerName))
        {
            sql.append(" and d.kehuName like :customerName  ");
            count.append(" and d.kehuName like :customerName  ");
        }
        if (!StringUtils.isBlank(customerTel))
        {
            sql.append(" and d.lxTel like :customerTel  ");
            count.append(" and d.lxTel like :customerTel  ");
        }
        if (!StringUtils.isBlank(mendianName))
        {
            sql.append(" and m.name like :mendianName  ");
            count.append(" and m.name like :mendianName  ");
        }
        if (!StringUtils.isBlank(dingDanUid))
        {
            sql.append(" and d.dingDanUid like :dingDanUid  ");
            count.append(" and d.dingDanUid like :dingDanUid  ");
        }
        if (!StringUtils.isBlank(buyType))
        {
            sql.append(" and d.buyType=:buyType  ");
            count.append(" and d.buyType=:buyType  ");
        }
        if (!StringUtils.isBlank(state))
        {
            sql.append(" and d.state=:state ");
            count.append(" and d.state=:state ");
        }

        if (null != fuwuzhan)
        {
            sql.append(" and (m.fuwuzhanId=:fuwuzhanId ");
            count.append(" and (m.fuwuzhanId=:fuwuzhanId ");
            if (StringUtils.isBlank(state) || state.equals(BuzConst.DINGDAN_STATES0) || state.equals(BuzConst.DINGDAN_STATES3) || state.equals(BuzConst.DINGDAN_STATES4))
            {
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    if (StringUtils.isBlank(state))
                    {
                        sql.append(" or (d.buyType='" + BuzConst.CARD_BUYTYPE_SM + "'  and d.mendianId is null  and  ");
                        count.append(" or (d.buyType='" + BuzConst.CARD_BUYTYPE_SM + "'  and d.mendianId is null  and  ");
                    }
                    else
                    {
                        sql.append(" or (d.buyType='" + BuzConst.CARD_BUYTYPE_SM + "' and d.state='" + state + "' and d.mendianId is null   and  ");
                        count.append(" or (d.buyType='" + BuzConst.CARD_BUYTYPE_SM + "' and d.state='" + state + "' and d.mendianId is null   and  ");
                    }
                    sql.append("  d.province like :province");
                    count.append("  d.province like :province");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        sql.append(" and d.city like :city");
                        count.append(" and d.city like :city");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            sql.append(" and d.town like :town");
                            count.append(" and d.town like :town");
                        }
                    }
                    sql.append(" )");
                    count.append(" )");
                }
            }
            sql.append(" )");
            count.append(" )");
        }
        else
        {
            if (!StringUtils.isBlank(fwzIds))
            {
                sql.append(" and (f.id in (" + fwzIds + ") " + fwzStr + ") ");
                count.append(" and (f.id in (" + fwzIds + ") " + fwzStr + ") ");
            }
            else if (null == fwzIds && fwzStr.length() > 0)
            {
                sql.append("  " + fwzStr);
                count.append("  " + fwzStr);
            }
        }
        String rsql = sql.toString();
        if (!StringUtils.isBlank(orderBy))
        {
            rsql += " order by " + orderBy;
            if (!StringUtils.isBlank(orderType))
            {
                rsql += "  " + orderType;
            }
        }
        else
        {
            rsql += " order by id desc ";
        }
        query = session.createSQLQuery(rsql).addScalar("id", StandardBasicTypes.LONG).addScalar("dingDanUid", StandardBasicTypes.STRING).addScalar("carNo", StandardBasicTypes.STRING).addScalar("userId", StandardBasicTypes.STRING).addScalar("kehuName", StandardBasicTypes.STRING).addScalar("lxTel", StandardBasicTypes.STRING).addScalar("address", StandardBasicTypes.STRING).addScalar("mendianId", StandardBasicTypes.LONG).addScalar("buyType", StandardBasicTypes.STRING).addScalar("goodsPrice", StandardBasicTypes.DOUBLE)
                .addScalar("servicePrice", StandardBasicTypes.DOUBLE).addScalar("lat", StandardBasicTypes.DOUBLE).addScalar("lng", StandardBasicTypes.DOUBLE).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("state", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("mendName", StandardBasicTypes.STRING).addScalar("mendImgUrl",
                        StandardBasicTypes.STRING).addScalar("fuwuzhanId", StandardBasicTypes.LONG).addScalar("fwzName", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(DingDanCard.class));

        if (!StringUtils.isBlank(customerName))
        {
            query.setString("customerName", "%" + customerName.trim() + "%");
        }
        if (!StringUtils.isBlank(customerTel))
        {
            query.setString("customerTel", "%" + customerTel.trim() + "%");
        }
        if (!StringUtils.isBlank(mendianName))
        {
            query.setString("mendianName", "%" + mendianName.trim() + "%");
        }
        if (!StringUtils.isBlank(dingDanUid))
        {
            query.setString("dingDanUid", "%" + dingDanUid.trim() + "%");
        }
        if (!StringUtils.isBlank(buyType))
        {
            query.setString("buyType", buyType);
        }
        if (!StringUtils.isBlank(state))
        {
            query.setString("state", state);
        }
        if (null != fuwuzhan)
        {
            query.setLong("fuwuzhanId", fuwuZhanId);
            if (StringUtils.isBlank(state) || state.equals(BuzConst.DINGDAN_STATES0) || state.equals(BuzConst.DINGDAN_STATES3) || state.equals(BuzConst.DINGDAN_STATES4))
            {
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    query.setString("province", fuwuzhan.getProvince() + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        query.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            query.setString("town", fuwuzhan.getTown() + "%");
                        }
                    }
                }
            }
        }
        if (pageSize > 0)
        {
            int from = (currentPage - 1) * pageSize;
            query.setFirstResult(from);
            query.setMaxResults(pageSize);
        }

        list = (List<DingDanCard>) query.list();
        query = session.createSQLQuery(count.toString()).addScalar("countNum", StandardBasicTypes.INTEGER);
        if (!StringUtils.isBlank(customerName))
        {
            query.setString("customerName", "%" + customerName.trim() + "%");
        }
        if (!StringUtils.isBlank(customerTel))
        {
            query.setString("customerTel", "%" + customerTel.trim() + "%");
        }
        if (!StringUtils.isBlank(mendianName))
        {
            query.setString("mendianName", "%" + mendianName.trim() + "%");
        }
        if (!StringUtils.isBlank(dingDanUid))
        {
            query.setString("dingDanUid", "%" + dingDanUid.trim() + "%");
        }
        if (!StringUtils.isBlank(buyType))
        {
            query.setString("buyType", buyType);
        }
        if (!StringUtils.isBlank(state))
        {
            query.setString("state", state);
        }
        if (null != fuwuzhan)
        {
            query.setLong("fuwuzhanId", fuwuZhanId);
            if (StringUtils.isBlank(state) || state.equals(BuzConst.DINGDAN_STATES0) || state.equals(BuzConst.DINGDAN_STATES3) || state.equals(BuzConst.DINGDAN_STATES4))
            {
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    query.setString("province", fuwuzhan.getProvince() + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        query.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            query.setString("town", fuwuzhan.getTown() + "%");
                        }
                    }
                }
            }
        }
        if (pageSize > 0)
        {
            int totalCount = (Integer) query.uniqueResult();
            int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
            json.setTotalSize(totalCount);
            json.setTotalPage(totalPage);
            json.setPageSize(pageSize);
            json.setCurrentPage(currentPage);
        }
        String hql = null;
        if (null != list && list.size() > 0)
        {
            for (DingDanCard o : list)
            {
                if (!StringUtils.isBlank(o.getCrateDate()))
                {
                    o.setInvalidDate(DateUtils.getDatePlusHour(o.getCrateDate(), BuzConst.FORMAT_STRING1, BuzConst.FORMAT_STRING2, BuzConst.HOUR48));
                }
                //附上服务站
                //根据省市县 查询服务站，多个只取1个
                if ((BuzConst.CARD_BUYTYPE_SM.equals(o.getBuyType())) && (StringUtils.isBlank(o.getFwzName())))
                {
                    if (!StringUtils.isBlank(o.getProvince()))
                    {
                        String p = o.getProvince();
                        if (p.length() > 3)
                        {
                            p.substring(0, 3);
                        }
                        if (!StringUtils.isBlank(o.getCity()))
                        {
                            String c = o.getCity();
                            if (c.length() > 3)
                            {
                                c.substring(0, 3);
                            }
                            if (!StringUtils.isBlank(o.getTown()))
                            {
                                String t = o.getTown();
                                if (t.length() > 3)
                                {
                                    t.substring(0, 3);
                                }
                                hql = "from   FuwuZhan   where province like :province and city like :city and town like :town ";
                                Query q = getCurrentSession().createQuery(hql);
                                q.setString("province", p + "%");
                                q.setString("city", c + "%");
                                q.setString("town", t + "%");
                                List<FuwuZhan> l = (List<FuwuZhan>) q.list();
                                if (null != l && l.size() > 0)
                                {
                                    FuwuZhan f = l.get(0);
                                    if (!StringUtils.isBlank(f.getName()))
                                    {
                                        o.setFuwuzhanId(f.getId());
                                        o.setFwzName(f.getName());
                                    }
                                }
                                else
                                {
                                    hql = "from   FuwuZhan   where province like :province and city like :city and (town ='请选择' or town is null) ";
                                    q = getCurrentSession().createQuery(hql);
                                    q.setString("province", p + "%");
                                    q.setString("city", c + "%");
                                    List<FuwuZhan> l2 = (List<FuwuZhan>) q.list();
                                    if (null != l2 && l2.size() > 0)
                                    {
                                        FuwuZhan f = l2.get(0);
                                        if (!StringUtils.isBlank(f.getName()))
                                        {
                                            o.setFuwuzhanId(f.getId());
                                            o.setFwzName(f.getName());
                                        }
                                    }
                                    else
                                    {
                                        hql = "from   FuwuZhan   where province like :province and (city ='请选择' or city is null) ";
                                        q = getCurrentSession().createQuery(hql);
                                        q.setString("province", p + "%");
                                        List<FuwuZhan> l3 = (List<FuwuZhan>) q.list();
                                        if (null != l3 && l3.size() > 0)
                                        {
                                            FuwuZhan f = l3.get(0);
                                            if (!StringUtils.isBlank(f.getName()))
                                            {
                                                o.setFuwuzhanId(f.getId());
                                                o.setFwzName(f.getName());
                                            }
                                        }
                                        else
                                        {
                                            o.setFwzName(BuzConst.DEWEI_NAME);
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }
        json.setResult(list);
        return json;
    }

    @Override
    public void update(DingDanCard model)
    {
        Session session = getCurrentSession();
        model.setUpdateDate(DateUtils.getCurrDate(null));
        session.update(model);

    }

    @Override
    public VoListPage<DingDanCard> queryMendDingdans(Long mid , Long id , int num)
    {
        VoListPage<DingDanCard> r = new VoListPage<DingDanCard>();
        r.setHasNext(false);

        Session session = getCurrentSession();
        StringBuilder sql = new StringBuilder();
        sql.append("select d.id,d.dingDanUid,d.carNo,d.userId,d.kehuName,d.lxTel,d.address,d.mendianId,d.buyType,d.goodsPrice,d.servicePrice, ");
        sql.append("d.lat,d.lng,d.crateDate,d.updateDate,d.state,d.province,d.city,d.town, ");
        sql.append("m.name as mendName,m.imageUrl as mendImgUrl ");
        //        sql.append(",f.id as fuwuzhanId,f.name as fwzName ");

        sql.append("from t_dingdan_card_main d  ");
        sql.append("left join t_mendian m on m.id=d.mendianId  ");
        //        sql.append("left join t_fuwuzhan f on m.fuwuzhanId =f.id  ");

        sql.append("where d.state in(0,1) and m.id=:mid ");
        if (null != id && id > 0)
        {
            sql.append(" and d.id<:id");
        }

        Query query = session.createSQLQuery(sql + " order by id desc ").addScalar("id", StandardBasicTypes.LONG).addScalar("dingDanUid", StandardBasicTypes.STRING).addScalar("carNo", StandardBasicTypes.STRING).addScalar("userId", StandardBasicTypes.STRING).addScalar("kehuName", StandardBasicTypes.STRING).addScalar("lxTel", StandardBasicTypes.STRING).addScalar("address", StandardBasicTypes.STRING).addScalar("mendianId", StandardBasicTypes.LONG).addScalar("buyType", StandardBasicTypes.STRING).addScalar(
                "goodsPrice", StandardBasicTypes.DOUBLE).addScalar("servicePrice", StandardBasicTypes.DOUBLE).addScalar("lat", StandardBasicTypes.DOUBLE).addScalar("lng", StandardBasicTypes.DOUBLE).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("state", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("mendName",
                StandardBasicTypes.STRING).addScalar("mendImgUrl", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(DingDanCard.class));
        query.setMaxResults(num);
        query.setLong("mid", mid);
        if (null != id && id > 0)
        {
            query.setLong("id", id);
        }
        List<DingDanCard> list = query.list();
        if (null != list && list.size() > 0)
        {
            r.setSuccess(true);
            if (list.size() == num)
            {
                r.setHasNext(true);
            }
            r.setCurrentId(list.get(list.size() - 1).getId());
            for (DingDanCard c : list)
            {
                c.setAllPrice(BuzConst.add(c.getGoodsPrice(), c.getServicePrice()));

                query = session.createQuery(" from  DingDanCardGoods where fid=:fid");
                query.setLong("fid", c.getId());
                List<DingDanCardGoods> l = query.list();
                c.setGoods(l);
            }
            r.setResult(list);
        }
        return r;
    }

    @Override
    public VoListPage<DingDanCard> queryMyDingdans(String wxid , Long id , int num)
    {
        VoListPage<DingDanCard> r = new VoListPage<DingDanCard>();
        r.setHasNext(false);

        Session session = getCurrentSession();
        StringBuilder sql = new StringBuilder();
        sql.append("select d.id,d.dingDanUid,d.carNo,d.userId,d.kehuName,d.lxTel,d.address,d.mendianId,d.buyType,d.goodsPrice,d.servicePrice, ");
        sql.append("d.lat,d.lng,d.crateDate,d.updateDate,d.state,d.province,d.city,d.town, ");
        sql.append("m.name as mendName,m.imageUrl as mendImgUrl ");
        //        sql.append(",f.id as fuwuzhanId,f.name as fwzName ");

        sql.append("from t_dingdan_card_main d  ");
        sql.append("left join t_mendian m on m.id=d.mendianId  ");
        //        sql.append("left join t_fuwuzhan f on m.fuwuzhanId =f.id  ");

        sql.append("where   d.userId=:wxid ");
        if (null != id && id > 0)
        {
            sql.append(" and d.id<:id");
        }

        Query query = session.createSQLQuery(sql + " order by id desc ").addScalar("id", StandardBasicTypes.LONG).addScalar("dingDanUid", StandardBasicTypes.STRING).addScalar("carNo", StandardBasicTypes.STRING)

        .addScalar("userId", StandardBasicTypes.STRING).addScalar("kehuName", StandardBasicTypes.STRING).addScalar("lxTel", StandardBasicTypes.STRING).addScalar("address", StandardBasicTypes.STRING).addScalar("mendianId", StandardBasicTypes.LONG).addScalar("buyType", StandardBasicTypes.STRING).addScalar("goodsPrice", StandardBasicTypes.DOUBLE).addScalar("servicePrice", StandardBasicTypes.DOUBLE).addScalar("lat", StandardBasicTypes.DOUBLE).addScalar("lng", StandardBasicTypes.DOUBLE).addScalar("crateDate",
                StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("state", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("mendName", StandardBasicTypes.STRING).addScalar("mendImgUrl", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(DingDanCard.class));
        query.setMaxResults(num);
        query.setString("wxid", wxid);
        if (null != id && id > 0)
        {
            query.setLong("id", id);
        }
        List<DingDanCard> list = query.list();
        if (null != list && list.size() > 0)
        {
            r.setSuccess(true);
            r.setCurrentId(list.get(list.size() - 1).getId());
            if (list.size() == num)
            {
                r.setHasNext(true);
            }
            for (DingDanCard c : list)
            {
                c.setAllPrice(BuzConst.add(c.getGoodsPrice(), c.getServicePrice()));
                query = session.createQuery(" from  DingDanCardGoods where fid=:fid");
                query.setLong("fid", c.getId());
                List<DingDanCardGoods> l = query.list();
                c.setGoods(l);
            }
            r.setResult(list);
        }
        return r;
    }
}